import { request } from './request'
import { ReputationScoreManager, type ScoreChange, type UserScoreData } from './reputationScore'

// 信誉分API服务
export class ReputationApiService {
  private static readonly BASE_URL = '/user/reputation'

  /**
   * 获取用户信誉分信息
   * @returns 用户信誉分数据
   */
  static async getUserReputationScore(): Promise<UserScoreData> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/score`,
        method: 'GET'
      })
      
      return response as UserScoreData
    } catch (error) {
      console.error('获取信誉分失败:', error)
      throw error
    }
  }

  /**
   * 获取信誉分历史记录
   * @param page 页码
   * @param pageSize 每页大小
   * @returns 历史记录列表
   */
  static async getReputationHistory(page: number = 1, pageSize: number = 20): Promise<{
    list: ScoreChange[]
    total: number
    page: number
    pageSize: number
  }> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/history`,
        method: 'GET',
        data: { page, pageSize }
      })
      
      return response as {
        list: ScoreChange[]
        total: number
        page: number
        pageSize: number
      }
    } catch (error) {
      console.error('获取历史记录失败:', error)
      throw error
    }
  }

  /**
   * 提交任务完成结果
   * @param taskId 任务ID
   * @param isCompleted 是否完成
   * @param hasPraise 是否获得好评
   * @param delayDays 延期天数
   * @returns 分数变化记录
   */
  static async submitTaskResult(
    taskId: string,
    isCompleted: boolean,
    hasPraise: boolean = false,
    delayDays: number = 0
  ): Promise<ScoreChange> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/task-result`,
        method: 'POST',
        data: {
          taskId,
          isCompleted,
          hasPraise,
          delayDays
        }
      })
      
      return response as ScoreChange
    } catch (error) {
      console.error('提交任务结果失败:', error)
      throw error
    }
  }

  /**
   * 提交考试结果
   * @param examId 考试ID
   * @param score 考试分数
   * @returns 分数变化记录
   */
  static async submitExamResult(examId: string, score: number): Promise<ScoreChange> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/exam-result`,
        method: 'POST',
        data: {
          examId,
          score
        }
      })
      
      return response as ScoreChange
    } catch (error) {
      console.error('提交考试结果失败:', error)
      throw error
    }
  }

  /**
   * 检查是否可以接取任务
   * @returns 是否可以接取任务
   */
  static async checkCanTakeTask(): Promise<{
    canTake: boolean
    currentScore: number
    minRequiredScore: number
    message?: string
  }> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/can-take-task`,
        method: 'GET'
      })
      
      return response as {
        canTake: boolean
        currentScore: number
        minRequiredScore: number
        message?: string
      }
    } catch (error) {
      console.error('检查任务接取权限失败:', error)
      throw error
    }
  }

  /**
   * 获取信誉分统计信息
   * @returns 统计信息
   */
  static async getReputationStats(): Promise<{
    currentScore: number
    totalTasks: number
    completedTasks: number
    failedTasks: number
    totalExams: number
    passedExams: number
    failedExams: number
    averageScore: number
    rank: number
    totalUsers: number
  }> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/stats`,
        method: 'GET'
      })
      
      return response as {
        currentScore: number
        totalTasks: number
        completedTasks: number
        failedTasks: number
        totalExams: number
        passedExams: number
        failedExams: number
        averageScore: number
        rank: number
        totalUsers: number
      }
    } catch (error) {
      console.error('获取统计信息失败:', error)
      throw error
    }
  }

  /**
   * 获取信誉分提升建议
   * @returns 建议列表
   */
  static async getReputationSuggestions(): Promise<{
    suggestions: string[]
    priority: 'high' | 'medium' | 'low'
    estimatedImprovement: number
  }> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/suggestions`,
        method: 'GET'
      })
      
      return response as {
        suggestions: string[]
        priority: 'high' | 'medium' | 'low'
        estimatedImprovement: number
      }
    } catch (error) {
      console.error('获取建议失败:', error)
      throw error
    }
  }

  /**
   * 重置信誉分（管理员功能）
   * @param userId 用户ID
   * @param reason 重置原因
   * @returns 操作结果
   */
  static async resetReputationScore(userId: string, reason: string): Promise<{
    success: boolean
    message: string
    newScore: number
  }> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/reset`,
        method: 'POST',
        data: {
          userId,
          reason
        }
      })
      
      return response as {
        success: boolean
        message: string
        newScore: number
      }
    } catch (error) {
      console.error('重置信誉分失败:', error)
      throw error
    }
  }

  /**
   * 导出信誉分报告
   * @param startDate 开始日期
   * @param endDate 结束日期
   * @returns 报告数据
   */
  static async exportReputationReport(
    startDate: string,
    endDate: string
  ): Promise<{
    reportUrl: string
    fileName: string
    fileSize: number
  }> {
    try {
      const response = await request({
        url: `${this.BASE_URL}/export-report`,
        method: 'POST',
        data: {
          startDate,
          endDate
        }
      })
      
      return response as {
        reportUrl: string
        fileName: string
        fileSize: number
      }
    } catch (error) {
      console.error('导出报告失败:', error)
      throw error
    }
  }
}

// 模拟API服务（用于开发测试）
export class MockReputationApiService {
  /**
   * 模拟获取用户信誉分信息
   */
  static async getUserReputationScore(): Promise<UserScoreData> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const mockHistory: ScoreChange[] = [
      ReputationScoreManager.createTaskRecord('网站开发', true, true, 0),
      ReputationScoreManager.createExamRecord('反作弊考试', 95),
      ReputationScoreManager.createTaskRecord('数据分析', true, false, 1),
      ReputationScoreManager.createTaskRecord('移动应用开发', false, false, 2),
      ReputationScoreManager.createExamRecord('安全测试', 88)
    ]
    
    // 调整时间戳
    mockHistory[1].timestamp = Date.now() - 86400000
    mockHistory[2].timestamp = Date.now() - 172800000
    mockHistory[3].timestamp = Date.now() - 259200000
    mockHistory[4].timestamp = Date.now() - 345600000
    
    return {
      currentScore: 85,
      initialScore: ReputationScoreManager.getInitialScore(),
      history: mockHistory
    }
  }

  /**
   * 模拟检查是否可以接取任务
   */
  static async checkCanTakeTask(): Promise<{
    canTake: boolean
    currentScore: number
    minRequiredScore: number
    message?: string
  }> {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const currentScore = 85
    const minRequiredScore = ReputationScoreManager.getMinTaskScore()
    
    return {
      canTake: ReputationScoreManager.canTakeTask(currentScore),
      currentScore,
      minRequiredScore,
      message: currentScore >= minRequiredScore ? '可以正常接取任务' : '信誉分过低，无法接取任务'
    }
  }

  /**
   * 模拟获取统计信息
   */
  static async getReputationStats(): Promise<{
    currentScore: number
    totalTasks: number
    completedTasks: number
    failedTasks: number
    totalExams: number
    passedExams: number
    failedExams: number
    averageScore: number
    rank: number
    totalUsers: number
  }> {
    await new Promise(resolve => setTimeout(resolve, 400))
    
    return {
      currentScore: 85,
      totalTasks: 15,
      completedTasks: 13,
      failedTasks: 2,
      totalExams: 5,
      passedExams: 4,
      failedExams: 1,
      averageScore: 87.5,
      rank: 156,
      totalUsers: 1250
    }
  }
} 